# 更新类别缓存
class UpdateTable:
    oldtypes = {}
    def update(self,model):
        self.oldtypes = types = model.query.all()
        # 将数组索引转化为typeid
        self.oldtypes = types = self.orderTypes(types, 'id')
        # 开始循环所有数据
        for index, item in types.items():
            arrparentid = self.arrParentid(index)
            arrchildid = self.arrChildid(index)
            # print("############", arrchildid.isdigit(),arrchildid)
            child = 0 if arrchildid.isdigit() else 1
            # 如果父栏目数组、子栏目数组，及是否含有子栏目不与原来相同，更新，字符串比较使用strcasecmp()方法，直接比较字符串会出问题
            if child != item.child or arrparentid != item.arrparentid or arrchildid != item.arrchildid:
                c = model.query.filter(model.id == index).first()
                c.arrparentid = arrparentid
                c.arrchildid = arrchildid
                c.child = child
        # 删除在非正常显示的栏目
        for index,item in types.items():
            if item.parentid != 0 and self.oldtypes.get(item.parentid) == None:
                # print("### 删除的数据 ###",item.id)
                model.query.filter(model.id == item.id).delete()

    # 以索引重排结果数组
    def orderTypes(self,types,id):
        tmp_arr = {}
        for i in types:
            tmp_arr[i.id] =  i
        return tmp_arr

    # 获取父栏目ID列表
    def arrParentid(self, pid, arrparentid=''):
        if len(self.oldtypes) <= 0 or self.oldtypes.get(pid) == None:
            return False
        parentid = self.oldtypes.get(pid).parentid
        if type(parentid) == int:
            parentid = str(parentid)
        arrparentid = parentid + ',' + arrparentid if arrparentid != '' else parentid
        if parentid != '0':
            arrparentid = self.arrParentid(int(parentid), arrparentid)
        else:
            self.oldtypes.get(pid).arrparentid = arrparentid
        parentid = self.oldtypes.get(pid).parentid
        return arrparentid

    # 获取子栏目ID列表
    def arrChildid(self, pid):
        arrchildid = str(pid)
        if len(self.oldtypes) > 0:
            for index,item in self.oldtypes.items():
                if item.parentid != 0 and item.parentid == pid and index != pid:
                    arrchildid = arrchildid + ',' + self.arrChildid(index)
        return arrchildid
